<template>
  <div class="page-card">
    <div class="table-toolbar">
      <el-input
        v-model="search"
        placeholder="输入学年名称或代码"
        clearable
        style="max-width: 240px"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        新增学年
      </el-button>
    </div>

    <el-table :data="academicYears" border v-loading="loading">
      <el-table-column prop="year_code" label="学年代码" width="120" />
      <el-table-column prop="year_name" label="学年名称" width="160" />
      <el-table-column prop="start_date" label="开始日期" width="120" />
      <el-table-column prop="end_date" label="结束日期" width="120" />
      <el-table-column prop="semester" label="学期" width="100">
        <template #default="{ row }">
          {{ row.semester === 1 ? '上学期' : '下学期' }}
        </template>
      </el-table-column>
      <el-table-column label="当前学年" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.is_current" type="success">当前学年</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button 
            v-if="!row.is_current"
            type="success" 
            link 
            @click="handleSetCurrent(row)"
          >
            设为当前学年
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学年代码" prop="year_code">
          <el-input v-model="form.year_code" placeholder="如：2024-2025" />
        </el-form-item>
        <el-form-item label="学年名称" prop="year_name">
          <el-input v-model="form.year_name" placeholder="如：2024-2025学年" />
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker
            v-model="form.start_date"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker
            v-model="form.end_date"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="form.semester">
            <el-option label="上学期" :value="1" />
            <el-option label="下学期" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="设为当前学年" prop="is_current">
          <el-switch v-model="form.is_current" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { 
  createAcademicYear, 
  deleteAcademicYear, 
  getAcademicYearList, 
  updateAcademicYear 
} from '@/api/academic'
import type { AcademicYear, AcademicYearPayload } from '@/types/academic'

const loading = ref(false)
const saving = ref(false)
const academicYears = ref<AcademicYear[]>([])
const search = ref('')
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<AcademicYearPayload>({
  year_code: '',
  year_name: '',
  start_date: '',
  end_date: '',
  semester: 1,
  status: 1,
  is_current: false
})

const rules: FormRules = {
  year_code: [{ required: true, message: '请输入学年代码', trigger: 'blur' }],
  year_name: [{ required: true, message: '请输入学年名称', trigger: 'blur' }],
  start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  end_date: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑学年' : '新增学年'))

const loadAcademicYears = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getAcademicYearList({ skip, limit: pagination.size })
    const keyword = search.value.trim().toLowerCase()
    academicYears.value = res.items.filter((item: any) => {
      if (!keyword) return true
      return (
        item.year_name.toLowerCase().includes(keyword) ||
        item.year_code.toLowerCase().includes(keyword)
      )
    })
    pagination.total = keyword ? academicYears.value.length : res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载学年数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadAcademicYears()
}

const handleSearch = () => {
  pagination.page = 1
  loadAcademicYears()
}

const resetForm = () => {
  Object.assign(form, {
    year_code: '',
    year_name: '',
    start_date: '',
    end_date: '',
    semester: 1,
    status: 1,
    is_current: false
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: AcademicYear) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, {
      year_code: row.year_code,
      year_name: row.year_name,
      start_date: row.start_date,
      end_date: row.end_date,
      semester: row.semester,
      status: row.status,
      is_current: row.is_current
    })
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 验证日期逻辑
  if (form.start_date && form.end_date && form.start_date >= form.end_date) {
    ElMessage.error('结束日期必须晚于开始日期')
    return
  }
  
  saving.value = true
  try {
    if (isEdit.value) {
      await updateAcademicYear(0, { ...form })
    } else {
      await createAcademicYear({ ...form })
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadAcademicYears()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleSetCurrent = async (row: AcademicYear) => {
  try {
    await ElMessageBox.confirm(
      `确认将【${row.year_name}】设为当前学年吗？这将影响其他学年的当前状态。`,
      '提示',
      { type: 'warning' }
    )
    
    // 先取消所有学年的当前状态
    const currentYears = academicYears.value.filter(y => y.is_current)
    for (const year of currentYears) {
      await updateAcademicYear(year.id, { ...year, is_current: false })
    }
    
    // 设置当前学年
    await updateAcademicYear(row.id, { ...row, is_current: true })
    ElMessage.success('已设为当前学年')
    loadAcademicYears()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '操作失败')
    }
  }
}

const handleDelete = async (row: AcademicYear) => {
  try {
    await ElMessageBox.confirm(
      `确认删除学年【${row.year_name}】吗？`,
      '提示',
      { type: 'warning' }
    )
    await deleteAcademicYear(row.id)
    ElMessage.success('已删除')
    loadAcademicYears()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '删除失败')
    }
  }
}

onMounted(() => {
  loadAcademicYears()
})
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>